//
//  MessagePayViewController.m
//  BGM
//
//  Created by 我要变好看 on 2018/12/11.
//  Copyright © 2018 com.alirtc.demo. All rights reserved.
//

#import "MessagePayViewController.h"
#import "Common.h"
#import "BGMHTTP.h"
#import <AlipaySDK/AlipaySDK.h>
#import "BGMUser.h"
#import "SVProgressHUD.h"


@interface MessagePayViewController ()

@property (nonatomic, strong)UITextField *payText;
@property (nonatomic, strong)NSString *orderID;

@property (nonatomic, assign)float money;



@end

@implementation MessagePayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    CGRect rect = self.titleBtn.frame;
    rect.size.width = rect.size.width+70;
    self.titleBtn.frame = rect;

    if (self.type == BGMPushildRed) {
        [self.titleBtn setTitle:@"帮转红包" forState:UIControlStateNormal];
    }else if(self.type == BGMThanksRed){
        [self.titleBtn setTitle:@"答谢红包" forState:UIControlStateNormal];
    }else if (self.type ==BGMAddRed ){
        [self.titleBtn setTitle:@"补加红包" forState:UIControlStateNormal];
        self.backBtn.hidden = NO;
    }

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(payResult:) name:@"AliPaySuccess" object:nil];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, self.navview.frame.size.height+15, SCREENW-30, 250)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 80, 60)];
    label1.text = @"付款方式";
    label1.textColor = bgmmainColor;
    [bgView addSubview:label1];
    
    UIView *aliView = [[UIView alloc]initWithFrame:CGRectMake(130, 15, 80, 30)];
    aliView.backgroundColor = [UIColor whiteColor];
    aliView.tag = 999;
    [bgView addSubview:aliView];
    
    UIImageView *payView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 3, 30, 25)];
    [payView setImage:[UIImage imageNamed:@"payicon"]];
    [aliView addSubview:payView];

    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, 50, 30)];
    label2.text = @"支付宝";
    label2.font = [UIFont boldSystemFontOfSize:15];
    label2.textColor = bgmyelloeColor;
    label2.tag = 100;
    [aliView addSubview:label2];
 
    
    UIView *appleView = [[UIView alloc]initWithFrame:CGRectMake(220, 15, 100, 30)];
    appleView.backgroundColor = [UIColor whiteColor];
    appleView.tag = 888;
    [bgView addSubview:appleView];
  
    
    
    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, SCREENW, 0.3)];
    line1.backgroundColor = [UIColor grayColor];
    line1.alpha = 0.1;
    [bgView addSubview:line1];
    
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(15, 70, 100, 30)];
    label3.text = @"红包总金额";
    label3.textColor = bgmmainColor;
    [bgView addSubview:label3];
    
    UILabel *line4 = [[UILabel alloc]initWithFrame:CGRectMake(15, 100, 30, 50)];
    line4.text = @"￥";
    line4.textColor = bgmmainColor;
    line4.font = [UIFont systemFontOfSize:25];
    [bgView addSubview:line4];
    
    self.payText = [[UITextField alloc]initWithFrame:CGRectMake(50, 100, 200, 50)];
    self.payText.keyboardType = UIKeyboardTypeDecimalPad;
    self.payText.returnKeyType = UIReturnKeyDone;
    self.payText.placeholder = @"输入金额";
    self.payText.font =[UIFont systemFontOfSize:25];
    [bgView addSubview:self.payText];
    
    UILabel *line2 = [[UILabel alloc]initWithFrame:CGRectMake(17, 150, bgView.frame.size.width-30, 0.3)];
    line2.backgroundColor = [UIColor grayColor];
    line2.alpha = 0.1;
    [bgView addSubview:line2];
    
    
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(15, 180, bgView.frame.size.width-30, 50)];
    btn.backgroundColor = bgmyelloeColor;
    btn.layer.cornerRadius = 5;
    btn.layer.masksToBounds = YES;
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:bgmmainColor forState:UIControlStateNormal];
    [bgView addSubview:btn];
    [btn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)payResult:(NSNotification *)notification{
    NSDictionary *resultDic = notification.object;
     NSString *code = [NSString stringWithFormat:@"%@",[resultDic objectForKey:@"resultStatus"]];
    if ([code isEqualToString:@"9000"]) {
        [self postNotificationCenterPaySuccess];
        [SVProgressHUD showSuccessWithStatus:@"支付成功"];
    }else{
        [SVProgressHUD showErrorWithStatus:@"支付失败"];
    }
    
}
- (void)clickBtn{
    [SVProgressHUD show];
    [self requestOrderID];
}


#pragma mark 支付宝支付
- (void)requestOrderID{
    NSString *str  = self.payText.text;
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (str.length <= 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入金额"];
        return;
    }
    
    self.money = [str floatValue];
    if (self.money<=0.0) {
        [SVProgressHUD showInfoWithStatus:@"金额不能少于0.01元"];
        return;
    }
    
    
    //生成订单
    if (self.type == BGMPushildRed) { //帮转红包
        NSDictionary *params = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId,@"total_amount":[NSString stringWithFormat:@"%.2f",self.money]};
        [BGMHTTP requestWithMethodName:@"publish/helpRedPacakgePay" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
                if ([code isEqualToString:@"200"]) {
                    NSString *data = [NSString stringWithFormat:@"%@",[result objectForKey:@"data"]];
                    self.orderID = data;
                    [self pay];
                }
            });
        }];
    }else if (self.type == BGMThanksRed){  //答谢红包
        
        NSDictionary *params = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId,@"total_amount":[NSString stringWithFormat:@"%.2f",self.money],@"acUsersId":self.thankUserID};
        [BGMHTTP requestWithMethodName:@"publish/acknowledge" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *data = [NSString stringWithFormat:@"%@",[result objectForKey:@"data"]];
                self.orderID = data;
                [self pay];
            });
        }];
        
     
    }else if (self.type == BGMAddRed){  //补发红包
        
        NSDictionary *params = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId,@"total_amount":[NSString stringWithFormat:@"%.2f",self.money],@"publishId":self.publishId};
        [BGMHTTP requestWithMethodName:@"publish/helpRedPacakgeSupplement" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *data = [NSString stringWithFormat:@"%@",[result objectForKey:@"data"]];
                self.orderID = data;
                [self pay];
            });
        }];
    }
    
  
}
- (void)pay{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *appScheme = @"com.suyou.banggemang";
        // NOTE: 调用支付结果开始支付
        dispatch_async(dispatch_get_main_queue(), ^{
            [[AlipaySDK defaultService] payOrder:self.orderID fromScheme:appScheme callback:^(NSDictionary *resultDic) {  //9000 成功
                NSString *code = [NSString stringWithFormat:@"%@",[resultDic objectForKey:@"resultStatus"]];
                if ([code isEqualToString:@"9000"]) {
                    [self postNotificationCenterPaySuccess];
                    [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                 }else{
                    [SVProgressHUD showErrorWithStatus:@"支付失败"];
                    
                }
            }];
        });
    });
}

- (void)postMoeny{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //类型（1 红包支付(只传 usersId)   2 帮转红包补加支付(传 usersId, publishId)   3 完成帮忙答谢支付（传usersId, acknowledgeUsers））
        NSDictionary *param;
        if (self.type == BGMPushildRed) {//帮转红包
            param = @{@"userToken":[BGMUser shareInstance].userToken,
                @"usersId":[BGMUser shareInstance].userId,
                @"type":@"1",
                @"money":[NSString stringWithFormat:@"%.2f",self.money]
            };
        }else if(self.type == BGMThanksRed){//答谢红包
            param = @{@"userToken":[BGMUser shareInstance].userToken,
                      @"usersId":[BGMUser shareInstance].userId,
                      @"acknowledgeUsers":self.thankUserID,
                      @"money":[NSString stringWithFormat:@"%.2f",self.money],
                      @"type":@"3",
                      };
        }else if (self.type ==BGMAddRed ){//补加红包
            param = @{@"userToken":[BGMUser shareInstance].userToken,
                      @"usersId":[BGMUser shareInstance].userId,
                      @"publishId":self.publishId,
                      @"money":[NSString stringWithFormat:@"%.2f",self.money],
                      @"type":@"2",
                      };
        }

        [BGMHTTP requestWithMethodName:@"alipay/paySuccrss" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
            NSLog(@"sdafsafasfsafa");
            NSLog(@"向后台发送支付金额");
        }];
    });
 
}


- (void)postNotificationCenterPaySuccess{
    [SVProgressHUD dismiss];
    if (self.thankUserID.length>0) {  //答谢好友
        [SVProgressHUD showSuccessWithStatus:@"答谢完成"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"pay_money_thanks" object:nil];
    }else{
        
    }
    
    if(self.type ==BGMAddRed){  //补加
        [[NSNotificationCenter defaultCenter]postNotificationName:@"add_pay_money" object:nil];
        [self clickBack];
    }else if (self.type == BGMThanksRed){ //答谢
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if (self.type == BGMPushildRed){ //帮转
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"pay_money" object:[NSString stringWithFormat:@"%.2f",self.money]];
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    [self performSelector:@selector(postMoeny) withObject:nil afterDelay:3];
    
}

- (void)clickBack{
    
    if (self.type == BGMPushildRed) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if(self.type == BGMThanksRed){
        [self.titleBtn setTitle:@"答谢红包" forState:UIControlStateNormal];
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if (self.type ==BGMAddRed ){
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}

- (void)dealloc{
    //移除观察者 self
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
